<template>
  <div class="container-fluid text-white">
    <!-- 面包屑 + 返回 -->
    <nav class="text-sm text-white/60 mb-6 flex items-center gap-2">
      <router-link to="/" class="hover:text-white">首页</router-link>
      <span>/</span>
      <span class="text-white/80">商品详情</span>
      <button class="ml-auto btn-outline px-3 py-1" @click="$router.back()">返回</button>
    </nav>
  
    <!-- 加载/错误/内容 -->
    <div v-if="loading" class="py-16 text-white/60">加载中…</div>
    <div v-else-if="!product" class="py-16 text-red-300">未找到该商品</div>
    <div v-else class="grid md:grid-cols-2 gap-8">
      <!-- 主图：使用 3:2 比例容器，避免不同尺寸图片拉伸；桌面端悬浮微缩放提升质感 -->
      <div class="relative w-full pt-[66%] bg-white/5 rounded-xl overflow-hidden border border-white/10 group">
        <img :src="product.imgSrc || '/images/apple.svg'" :alt="product.name"
             class="absolute inset-0 w-full h-full object-cover object-center transition-transform duration-300 ease-out group-hover:scale-[1.03] select-none"
             loading="lazy" decoding="async" referrerpolicy="no-referrer" draggable="false"
             @error="onImgError" />
      </div>
      <div>
        <h1 class="text-3xl font-bold tracking-tight">{{ product.name }}</h1>
        <p class="text-white/60 mt-3 leading-7">{{ product.brief }}</p>
        <div class="flex items-center gap-4 mt-5">
          <div class="text-3xl text-emerald-400 font-extrabold">￥{{ product.price }}</div>
        </div>
<div class="mt-8 flex items-center gap-3">
          <div class="inline-flex items-center gap-2">
            <button class="px-3 py-2 rounded-full border border-white/15" @click="dec">-</button>
            <input v-model.number="qty" type="number" min="1" class="w-16 text-center input-control px-2 py-2" />
            <button class="px-3 py-2 rounded-full border border-white/15" @click="inc">+</button>
          </div>
          <button class="btn-primary" @click="addToCart">加入购物车</button>
          <router-link to="/checkout"@click="addOrder" class="btn-outline">去结算</router-link>
        </div>
      </div>
    </div>
  
    <div v-if="product" class="mt-12">
      <h2 class="text-xl font-semibold mb-3">商品详情</h2>
      <p class="text-white/70 leading-7">{{ product.desc }}</p>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import toast from '../composables/toast'
import { useRoute } from 'vue-router'
import { getProducts } from '../api/ProductsAPI.js'

const route = useRoute()
const product = ref(null)
const loading = ref(true)
const qty = ref(1)

// 图片加载失败占位：当主图加载失败时使用兜底图片
function onImgError(e){ e.target.src = '/images/apple.svg' }

// 加载当前商品详情：根据路由参数 id 在本地 JSON 中查找
async function load(){
  loading.value = true
  try{
    // 复用列表接口：按 productId 精确过滤，取一条
    const resp = await getProducts({ productId: route.params.productId, pageNum: 1, pageSize: 1 })
    const page = resp?.data?.data
    product.value = page?.list?.[0] || null
  } finally {
    loading.value = false
  }
}

// 生命周期：首次进入与 id 变化时均重新加载
onMounted(load)
watch(() => route.params.id, load)

// 加入购物车：合并数量、写入本地并广播更新事件
function addToCart(){
  if(!product.value) return
  const raw = JSON.parse(localStorage.getItem('cart')||'[]')
  // 统一主键：优先 productId，再用 id；统一转字符串
  const pid = String(product.value?.productId ?? product.value?.id ?? '')
  if(!pid){ toast.error('商品ID缺失，无法加入购物车'); return }
  const idx = raw.findIndex(i => String(i.id) === pid)
  if (idx > -1) raw[idx].qty += qty.value
  else raw.push({ id: pid, name: product.value.name, price: Number(product.value.price)||0, cover: product.value.cover, qty: qty.value })
  localStorage.setItem('cart', JSON.stringify(raw))
  window.dispatchEvent(new CustomEvent('cart-updated'))
  toast.success('已加入购物车')
}

function addOrder(){
  // const payload = {
  //   customerId: auth.user.id,
  //   addressId: selectedAddressId.value || undefined,
  //   orderItems: items,
  //   paymentMethod: 'alipay'
  // }
  // try{
  //   const resp = await createOrder(payload)
  //   const { code, data, msg } = resp?.data || {}
  //   if(code !== 200){ throw new Error(msg || '下单失败') }
  //   // 优先从返回体中取订单号（兼容不同字段名）
  //   const oidFromResp = data?.orderNo || data?.orderId || data?.order_id || (typeof data === 'object' ? data?.id : null)
  //   if(oidFromResp){
  //     orderId.value = String(oidFromResp)
  //   } else {
  //     // 回退方案：查询当前用户最新订单
  //     const latestId = await fetchLatestOrderIdForCustomer(auth.user.id)
  //     if(latestId){
  //       orderId.value = String(latestId)
  //     }
  //   }
  //   if(!orderId.value){ throw new Error('未获取到订单号') }
  //   toast.success('订单已提交，正在跳转支付')
  //   return true
  // }catch(e){ toast.error(e.message || '下单失败'); throw e }

}

// 数量加减：最小为 1，避免出现 0 或负数
function inc(){ qty.value++ }
function dec(){ if(qty.value>1) qty.value-- }
</script>